package cn.jaychang.demo5.auth.server.config;

import cn.jaychang.demo5.auth.server.extension.mobile.MobilePasswordAuthenticationSecurityConfig;
import cn.jaychang.demo5.auth.server.service.impl.JwtTokenUserDetailsService;
import lombok.AllArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

/**
 * @author jaychang
 * @since 2024/5/20
 **/
@Configuration
@AllArgsConstructor
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    private final JwtTokenUserDetailsService jwtTokenUserDetailsService;

    private final MobilePasswordAuthenticationSecurityConfig mobilePasswordAuthenticationSecurityConfig;

    /**
     * 配置用户
     * @param auth
     * @throws Exception
     */
    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        // 从数据库中查询用户信息
        auth.userDetailsService(jwtTokenUserDetailsService);
    }

    /**
     * AuthenticationManager在密码授权模式下会用到，这里提前注入，如果你用的不是密码模式，可以不注入
     *
     * @return
     * @throws Exception
     */
    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    /**
     * 配置安全拦截策略
     *
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(final HttpSecurity http) throws Exception {
        // @formatter:off
        http
                // 添加自定义oauth认证模式
                .apply(mobilePasswordAuthenticationSecurityConfig)
                .and()
                .authorizeRequests()
                //注销的接口需要放行
                .antMatchers("/oauth/logout","/oauth/login").permitAll()
                .anyRequest().authenticated();


                http.formLogin()
                        // form表单提交登录的url
                        .loginProcessingUrl("/login")
                        // form表单登录的页面，自定义登录页面的跳转
                        .loginPage("/oauth/login");

        http.csrf().disable();
        // @formatter:on
    }

}
